<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------
namespace app\api\controller\v1;

use app\api\controller\Base;
use service\ApiReturn;
use think\Db;

/**
 * 客服聊天
 * @author 晓风<215628355@qq.com>
 * @date 2020年12月14日15:07:54
 * Class StoreChat
 */
class StoreChat extends Base
{
    
   /**
     * 聊天鉴权--仅限用户端
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function getAuth($data = [] , $user = []){  
        Db::startTrans();
        try{            
            $data['session_title'] = $data['session_title'] ??  "";
            $result = \app\customer\model\Chat::addUserMessageInfo($data['store_id'],$user["id"], $data['type'],$data['content'] , $data['session_title']);
            Db::commit();            
        }catch(\Exception $e){
            Db::rollback();
            return ApiReturn::r(0, [
                "err_code"=> $e->getCode(),
                "err_msg"=>$e->getMessage(),        
            ], $e->getMessage());
        }       
        $message = [
            "msgid"=> $result['msgid'],    
            "type"=> $result['type'],      
            "content"=> $result['content'],   
            "user_id"=>$user["id"],
            "store_id"=> $data['store_id'], 
            "service_user_id"=> $result['service_user_id'],
            "nickname"=>  $user['user_nickname'],    
            "head_img"=>  get_thumb($user["head_img"]),           
            "form_type"=>$result['form_type'],   
            "create_time"=>date("Y-m-d H:i:s",$result["create_time"]),
            "session_title"=>$result['session_title'],
            "store_name"=>  $result['store_name'],    
            "store_logo"=>  get_thumb($result["store_logo"])
        ];
        return ApiReturn::r(1,[
            "err_code" =>  $result["service_user_id"] ? 0 : 5002,
            "offline"  =>  $result["service_user_id"] ? 0 : 1,
            "err_msg"  =>  $result["service_user_id"] ?: "客服不在线，请稍候再咨询",
            "to_uid"   =>  $result['service_user_id'],
            "message"  =>  $message          
        ],"success");
    }
    /**
     * 我的会话列表-用户端
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function getSession($data = [] , $user = []){ 

        $lists = \app\customer\model\Session::getSessionList($user['id']);
        $info = [];
        foreach($lists as $item){
            $item['noread'] =  $item["user_noread"];   
            $item['head_img'] =  get_thumb($item["head_img"]);
            //$item['update_time'] = date("Y-m-d H:i:s",  $item['update_time']);
            $info[] = $this->filter($item);
        }
        return ApiReturn::r(1,$this->getThinkPage($lists,$info),"success");
    }
    
      /**
     * 获取与门店的聊天记录-用户端
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function getList($data = [] , $user = []){ 
        
        $store = \app\customer\model\Shop::field("store_name as user_nickname,store_logo as head_img")
            ->where("store_id", $data["store_id"])
            ->find();
        if(!$store){
            return ApiReturn::r(0,[],"店铺不存在");   
        }  
    
        $store['head_img'] = get_file_url($store["head_img"]);
        $user['head_img'] = get_file_url($user["head_img"]);
        
        if(!$data["size"]){
            $data["size"] = 10;
        }      
        $data["msgid"] = $data["msgid"] ?? "";
        $lists = \app\customer\model\Chat::getUserStoreMsgList($user['id'],$data["store_id"],0, $data["msgid"],$data["size"]);
        $info = [];
        foreach($lists as $item){
            $member = $item["form_type"]  == 2 ?  $store :$user;     
            $item['head_img'] = $member['head_img'];
            $item['nickname'] =  $member['user_nickname'];
            //$item['create_time'] = date("Y-m-d H:i:s",  $item['create_time']);
            $info[] = $this->filter($item);
        }
        return ApiReturn::r(1,$info,"success");
    }
    /**
     * 删除会话-用户端 
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function delSession($data = [] , $user = []){   
        Db::startTrans();
        try{            
            \app\customer\model\Session::delSession($user["id"], $data['store_id'],1);
            Db::commit();            
        }catch(\Exception $e){
            Db::rollback();
            return ApiReturn::r(0, "", $e->getMessage());
        }          
        return ApiReturn::r(1,"","success");
    }
    /**
     * 撤回消息-用户端
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function recallMessage($data = [] , $user = []){   
        Db::startTrans();
        try{            
            \app\customer\model\Chat::recallMessage($user["id"], $data['msgid']);
            Db::commit();            
        }catch(\Exception $e){
            Db::rollback();
            return ApiReturn::r(0, "", $e->getMessage());
        }          
        return ApiReturn::r(1,"","success");
    }
    
    /**
     * 设置已读
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function setRead($data = [] , $user = []){   
        Db::startTrans();
        try{            
            $ids = $data['store_id'] ?  explode(",",$data['store_id']) : [];
            \app\customer\model\Session::clearSessionNoReadIds($user["id"], $ids);
            Db::commit();            
        }catch(\Exception $e){
            Db::rollback();
            return ApiReturn::r(0, "", $e->getMessage());
        }          
        return ApiReturn::r(1,"","success");
    }
    
     /**
     * 获取登录票据
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function getUserSig($data = [] , $user = []){
        $userSig = \app\customer\model\Chat::getUserSig($user["id"]);        
        return ApiReturn::r(1,$userSig,"success");
    }
     /**
     * 获取H5聊天地址
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function getChatUrl($data = [] , $user = []){
        $goods_id = $data["goods_id"] ?? 0;
        $sku_id = $data["sku_id"] ?? 0; 
        $order_sn = $data["order_sn"] ?? 0;
        
        $arr = [
           "goods_id"=>$goods_id,
           "sku_id"=>$sku_id,
           "order_sn"=>$order_sn 
        ];
        $arr = array_filter($arr);
        try{ 
            $shop = \app\customer\model\Chat::getChatUrl($user["id"],$data["store_id"] , $arr);     
        }catch(\Exception $e){                     
            return ApiReturn::r(0,[],$e->getMessage());
        }         
        $shop["store_logo"] = $shop["store_logo"] ? get_file_url($shop["store_logo"]) : "";
        return ApiReturn::r(1,$this->filter($shop),"success");
        
    }
    
      /**
     * 获取H5聊天地址
     * @author 晓风<215628355@qq.com>     
     * @return mixed
     */
    public function getServiceUrl($data = [] , $user = []){
 
        try{ 
            $data["store_id"] = $data["store_id"] ?? 0;
            $shop = \app\customer\model\Chat::getServiceUrl($user["id"],$data["store_id"]);     
        }catch(\Exception $e){                     
            return ApiReturn::r(0,[],$e->getMessage());
        }    
        return ApiReturn::r(1,$this->filter($shop),"success");        
    }
    
}